<template>
    <div class="common-layout">
      <el-container>
        <el-header class="header-container">
          <div class="logo">
            <img src="../img/yz.webp" alt="永泽游戏网" />
            <span class="yz">永泽游戏网 - 管理员后台</span>
          </div>
          <div class="header-right">
        <el-button type="danger" @click="logout">退出登录</el-button>
          </div>
        </el-header>
        <el-container>
          <el-aside width="200px">
            <el-scrollbar>
                  <el-menu>
                  <el-sub-menu index="1">
                    <template #title>
                    <el-icon><setting /></el-icon>
                    <span>管理员功能</span>
                  </template>
                      <el-menu-item-group>
                      <el-menu-item index="1-1">
                          <router-link to="/checkGames">游戏管理</router-link>
                      </el-menu-item>
                      <el-menu-item index="1-2">
                          <router-link to="/home">通知公告管理</router-link>
                      </el-menu-item>
                      <el-menu-item index="1-3">
                          <router-link to="/user">用户管理</router-link>
                      </el-menu-item>
                      <el-menu-item index="1-4">
                          <router-link to="/category">游戏分类管理</router-link>
                      </el-menu-item>
                      <el-menu-item index="1-4">
                      <router-link to="/changeComments">评论管理</router-link>
                    </el-menu-item>
                      </el-menu-item-group>
                  </el-sub-menu>
                  </el-menu>
              </el-scrollbar>
          </el-aside>
          <el-main>
            <el-dialog v-model="centerDialogVisible" title="新增" width="500" center>
                        <el-form :inline="true" :model="Inline" ref="userForm" class="demo-form-inline">
                            <el-form-item label="分类名称" prop="name">
                              <el-input v-model="Inline.name" placeholder="分类名称" clearable />
                            </el-form-item>
                            <el-form-item label="排序" prop="sort">
                              <el-input v-model="Inline.sort" placeholder="排序" clearable />
                            </el-form-item>
                            <el-form-item>
                              <el-button type="primary" @click="cancel">取消</el-button>
                            </el-form-item>
                            <el-form-item>
                              <el-button type="primary" @click="save">提交</el-button>
                            </el-form-item>
                          </el-form>
                      </el-dialog>
                      <el-form :inline="true" :model="formInline" class="demo-form-inline">
                          <el-form-item label="名称">
                          <el-input v-model="formInline.user" placeholder="名称" v-on:keyup.enter.native="onSubmit" clearable />
                          </el-form-item>
                          <el-form-item>
                          <el-button type="primary" @click="onSubmit">查询</el-button>
                          </el-form-item>
                          <el-form-item>
                          <el-button type="primary" @click="centerDialogVisible = true">新增</el-button>
                          </el-form-item>
                      </el-form>
                      <el-table :data="tableData" border>
                        <el-table-column prop="name" label="分类名称" width="250" />
                        <el-table-column prop="sort" label="排序" width="200" />
                        <el-table-column prop="status" label="状态" width="130">
                          <template #default=" {row} ">
                            <el-tag :type="row.status === 0 ? 'danger' : 'success'" disable-transitions>
                              <el-icon v-if="row.status === 0 " size="16">
                                <close />
                              </el-icon>
                              <el-icon v-else size="16">
                                <check />
                              </el-icon>
                              {{ row.status === 0 ? '禁用' : '启用' }}
                            </el-tag>
                          </template>
                        </el-table-column>
                        <el-table-column prop="updateTime" label="操作时间" width="300" />
                        <el-table-column prop="operate" label="操作" width="300">
                          <template #default="{ row }">
                            <el-button type="success" @click="onMod(row)">编辑</el-button>
                            <el-button type="danger" @click="onDelete(row)">删除</el-button>
                            <el-button
                              :type="row.status === 1 ? 'success' : 'danger'"
                              @click="toggleStatus(row)"
                            >
                              {{ row.status === 0 ? '启用' : '禁用' }}
                            </el-button>
                          </template>
                        </el-table-column>
                      </el-table> 
                      <el-pagination @current-change="handleCurrentChange"
                        :current-page="pageNum" :page-sizes="pageSize"
                        layout="prev, pager, next" :total="50">
                      </el-pagination>
                      <el-dialog v-model="centerDialog" title="提示" width="500" center>
                        <span>
                          确认删除嘛？
                        </span>
                        <template #footer>
                          <div class="dialog-footer">
                            <el-button @click="centerDialog = false">取消</el-button>
                            <el-button type="primary" @click="doDelete">
                              确认
                            </el-button>
                          </div>
                        </template>
                      </el-dialog>
          </el-main>
        </el-container>
      </el-container>
    </div>
  </template>

<script setup>
import { useRouter } from 'vue-router';
const router = useRouter();
import {RouterLink,RouterView} from 'vue-router' 
// src/request/axiosInstance .js
import request from "../axios/request.js";
import { ElMessage } from 'element-plus'
import { onMounted, reactive,ref,computed,unref } from 'vue'
import { useAuthStore } from '../stores/userStore';

const store = useAuthStore();
const token = localStorage.getItem('token');
const pageKey = computed(() => {
  const storedPageKey = sessionStorage.getItem('pageKey');
  return storedPageKey || `${router.path || '/game'}-${Math.random().toString(36).substr(2, 9)}`;
});


const formInline = reactive({
  user: ''
})
const Inline=reactive({
  name: '',
  status: '',
  updateTime: '',
  sort: '',
  id: ''
})
const centerDialog=ref(false)
const centerDialogVisible=ref(false)
const pageSize=ref(15)
const pageNum=ref(1)
const total=ref(50)

const userForm = ref();
const cancel = () => {
    centerDialogVisible.value=false;
    userForm.value.resetFields();  
};
const forceUpdate = () => {
  tableData.value = [...tableData.value];
};

const save=()=>{
  if(Inline.id){
    request({
  url: '/category/mod',
  method: 'post',
  data:{
    "id":Inline.id,
    "name":Inline.name,
    "sort":Inline.sort,
  },
  pageKey: pageKey.value,
}).then((res) => {
  if(res.data.code==200){
    ElMessage({
    message: '更改成功',
    type: 'success',
    plain: true,
  })
  if (userForm.value) {
    userForm.value.resetFields()
  }
  centerDialogVisible.value=false
  callApi()
  }else{
    ElMessage({
    message: '更改失败',
    type: 'error',
    plain: true,
  })
  }
}).catch((err) => {
  console.log(err)
})
  }else{
  request({
  url: '/category/save',
  method: 'post',
  data:{
    "name":Inline.name,
    "sort":Inline.sort,
  },
  pageKey: pageKey.value,
}).then((res) => {
  if(res.data.code==200){
    ElMessage({
    message: '添加成功',
    type: 'success',
    plain: true,
  })
  if (userForm.value) {
    userForm.value.resetFields()
  }
  centerDialogVisible.value=false
  callApi()
  }else{
    ElMessage({
    message: '添加失败',
    type: 'error',
    plain: true,
  })
  }
}).catch((err) => {
  console.log(err)
})
  }
}

const paginateData = (page, size, Data) => {
	const startIndex = (page - 1) * size;
  const endIndex = startIndex + size;
	return Data.slice(startIndex, endIndex);
}
const tableData = ref([])

const callApi = () => {
  request({
    url: '/category/listPage',
    method: 'post',
    data: {
      pageSize: pageSize.value,
      pageNum: pageNum.value,
      param: { name: formInline.user },
    },
    pageKey: pageKey.value,
  })
    .then((res) => {
      if (res.data.code === 200) {
        tableData.value = res.data.data; // 更新数据源
        forceUpdate();
      } else {
        ElMessage.error('获取数据失败');
      }
    })
    .catch((err) => {
      console.error(err);
      ElMessage.error('请求失败，请检查网络');
    });
};


onMounted(() => {
 callApi();
});

// let currentTableData=computed(()=>{
//   return paginateData(pageNum.value, pageSize.value, tableData.value)
// }) 
// console.log(currentTableData.value)

const handleCurrentChange = (val) => {
		pageNum.value = val
    callApi()
    
}

const onSubmit = () => {
  callApi()
}

const onMod=(row)=>{
  Inline.id=row.id
  Inline.updateTime=row.updateTime
  Inline.name=row.name
  Inline.sort=row.sort

  centerDialogVisible.value=true;
}
let id=ref()
const onDelete = (row) => {
  id.value=row.id
  centerDialog.value=true;
}
const doDelete=()=>{
  request({
  url: '/category/delete?id='+id.value,
  method: 'get',
  pageKey: pageKey.value,
}).then((res) => {
  if(res.data.code==200){
    ElMessage({
    message: '删除成功',
    type: 'success',
    plain: true,
  })
  centerDialog.value=false
  callApi()
  }else{
    ElMessage({
    message: '删除失败',
    type: 'error',
    plain: true,
  })
  }
}).catch((err) => {
  console.log(err)
})
}

const toggleStatus = (row) => {// 切换状态
  request({
    url: '/category/status',
    method: 'post',
    data: {
      "id": row.id,
      "status": row.status, // 更新后的状态
      "name":row.name,
      "sort": row.sort
    },
    pageKey: pageKey.value,
  })
    .then((res) => {
      if (res.data.code === 200) {
        ElMessage({
          message: '状态更改成功',
          type: 'success',
          plain: true,
        });
        callApi(); // 重新加载表格数据
      } else {
        ElMessage({
          message: '状态更改失败',
          type: 'error',
          plain: true,
        });
      }
    })
    .catch((err) => {
      console.error(err);
      ElMessage({
        message: '请求失败，请检查网络连接',
        type: 'error',
        plain: true,
      });
    });
};

const logout = () => {
  // 清除本地存储中的 token 或用户信息
  request({
    url: '/login/logout',
    method: 'get',
    pageKey: pageKey.value,

  })
    .then((res) => {
      if (res.data.code === 200) {
              // 提示用户退出成功
        ElMessage({
          message: '退出登录成功',
          type: 'success',
        });
        store.logout(pageKey.value);
        // 跳转到登录页面
        router.push('/');
      } else {
        ElMessage.error('退出登录失败');
      }
    })
    .catch((err) => {
      console.error(err);
      ElMessage.error('请求失败，请检查网络');
    });

};
  

</script>
<style scoped>
.common-layout {
  background: #f4f6f9; /* 浅灰蓝色背景 */
  min-height: 100vh;
  padding-bottom: 50px;
}

.el-container {
  border-radius: 10px;
  overflow: hidden;
  box-shadow: 0px 4px 8px rgba(0, 0, 0, 0.1);
}

.header-container {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px;
  background-color: #2c3e50; /* 深蓝色头部 */
  color: #fff;
  box-shadow: 0px 4px 8px rgba(0, 0, 0, 0.1);
}

.header-container .logo {
  display: flex;
  align-items: center;
  gap: 15px;
}

.header-container .logo img {
  height: 50px;
}

.header-container .yz {
  font-size: 1.5rem;
  font-weight: bold;
}

.header-right {
  display: flex;
  align-items: center;
  gap: 15px;
}

/* 侧边栏样式 */
.el-aside {
  background-color: #fff;
  border-right: 1px solid #e6e6e6;
}

.el-menu {
  border: none;
}

.el-menu-item a {
  text-decoration: none;
  color: #303133;
}

.el-menu-item.is-active {
  background-color: #3498db;
  color: #fff;
}

/* 主内容区域 */
.el-main {
  background: #fff;
  padding: 20px;
  border-radius: 10px;
  box-shadow: 0px 4px 8px rgba(0, 0, 0, 0.1);
  margin: 20px;
}

/* 表单样式 */
.demo-form-inline {
  margin-bottom: 20px;
}

.el-form-item {
  margin-right: 15px;
}

.el-input {
  width: 200px;
}

/* 表格样式 */
.el-table {
  border-radius: 8px;
  overflow: hidden;
}

.el-table th {
  background-color: #3498db; /* 蓝色表头 */
  color: #fff;
  font-weight: bold;
}

.el-table td {
  vertical-align: middle;
}

/* 按钮样式 */
.el-button[type="primary"] {
  background-color: #3498db;
  border: none;
}

.el-button[type="primary"]:hover {
  background-color: #2980b9;
}

.el-button[type="success"] {
  background-color: #2ecc71;
  border: none;
}

.el-button[type="success"]:hover {
  background-color: #27ae60;
}

.el-button[type="danger"] {
  background-color: #e74c3c;
  border: none;
}

.el-button[type="danger"]:hover {
  background-color: #c0392b;
}

/* 分页样式 */
.el-pagination {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}

/* 对话框样式 */
.el-dialog {
  border-radius: 10px;
  box-shadow: 0px 4px 8px rgba(0, 0, 0, 0.2);
}

.dialog-footer {
  text-align: center;
  padding: 15px;
}

/* 标签样式 */
.el-tag[type="success"] {
  background-color: #2ecc71;
}

.el-tag[type="danger"] {
  background-color: #e74c3c;
}
</style>
